package com.iflytek.aidemo.student;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.iflytek.aidemo.R;
import com.iflytek.aidemo.api.ApiService;
import com.iflytek.aidemo.api.ApiServiceImpl;
import com.iflytek.aidemo.model.ApiResponse;
import com.iflytek.aidemo.model.WrongQuestionRecord;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WrongQuestionActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private WrongQuestionAdapter adapter;
    private List<WrongQuestionRecord> wrongList = new ArrayList<>();
    private List<Object> groupedItems = new ArrayList<>();
    private ApiService apiService = new ApiServiceImpl();
    private Button btnPractice;
    private ImageView btnBack;
    private ImageView btnBell;
    private View redDotBell;
    private Spinner spinnerTimeFilter;
    private String studentId;

    private enum TimeFilter { ALL, WEEK, MONTH }
    private TimeFilter currentFilter = TimeFilter.ALL;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wrong_question);
        studentId = getIntent().getStringExtra("student_id");

        if (studentId != null && !studentId.isEmpty()) {
            loadWrongQuestions(studentId);
        } else {
            Toast.makeText(this, "学生ID无效", Toast.LENGTH_SHORT).show();
        }

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new WrongQuestionAdapter(groupedItems);
        recyclerView.setAdapter(adapter);

        // 返回按钮
        btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 关闭当前Activity，返回上一页
            }
        });

        // 铃铛与红点
        btnBell = findViewById(R.id.btn_bell);
        redDotBell = findViewById(R.id.red_dot_bell);
        if (btnBell != null) {
            btnBell.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 若本周已处理（删除或保留），提示已完成
                    String weekKey = WrongPushStore.currentWeekKey();
                    boolean cleared = WrongPushStore.isClearedForWeek(WrongQuestionActivity.this, studentId, weekKey);
                    if (cleared) {
                        Toast.makeText(WrongQuestionActivity.this, "上周练习已完成或者上周无错题", Toast.LENGTH_SHORT).show();
                        // 隐藏红点
                        if (redDotBell != null) {
                            redDotBell.setVisibility(View.GONE);
                        }
                        return;
                    }

                    // 仅处理“上周练习”快捷入口
                    List<WrongQuestionRecord> lastWeekList = getLastWeekWrongList(wrongList);
                    if (lastWeekList == null || lastWeekList.isEmpty()) {
                        // 显示没有错题的提示
                        new AlertDialog.Builder(WrongQuestionActivity.this)
                            .setTitle("提示")
                            .setMessage("上周没有错题")
                            .setPositiveButton("确定", null)
                            .show();
                        
                        // 隐藏红点
                        if (redDotBell != null) {
                            redDotBell.setVisibility(View.GONE);
                        }
                        
                        // 标记为已处理，避免重复提示
                        WrongPushStore.markClearedForWeek(WrongQuestionActivity.this, studentId, weekKey, true);
                        return;
                    }
                    new androidx.appcompat.app.AlertDialog.Builder(WrongQuestionActivity.this)
                            .setTitle("上周错题练习")
                            .setMessage("是否开始完成上周的错题重练？")
                            .setPositiveButton("开始", (d, w) -> startPracticeFromPush(lastWeekList))
                            .setNegativeButton("取消", null)
                            .show();
                }
            });
        }

        // 时间筛选
        spinnerTimeFilter = findViewById(R.id.spinner_time_filter);
        spinnerTimeFilter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 1: currentFilter = TimeFilter.WEEK; break;
                    case 2: currentFilter = TimeFilter.MONTH; break;
                    default: currentFilter = TimeFilter.ALL; break;
                }
                applyGroupingAndFilter();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) { }
        });

        // 错题重练按钮
        btnPractice = findViewById(R.id.btn_practice);
        btnPractice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    System.out.println("错题列表大小: " + wrongList.size());
                    if (wrongList.isEmpty()) {
                        Toast.makeText(WrongQuestionActivity.this, "没有错题可以练习", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 根据时间范围计算本周与上周的错题
                    List<WrongQuestionRecord> thisWeekList = getThisWeekWrongList(wrongList);
                    List<WrongQuestionRecord> lastWeekList = getLastWeekWrongList(wrongList);

                    if ((thisWeekList == null || thisWeekList.isEmpty()) && (lastWeekList == null || lastWeekList.isEmpty())) {
                        new AlertDialog.Builder(WrongQuestionActivity.this)
                                .setMessage(getString(R.string.no_wrong_both))
                                .setPositiveButton(android.R.string.ok, null)
                                .show();
                        return;
                    }

                    // 弹出底部选项
                    showPracticeOptions(thisWeekList, lastWeekList);

                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(WrongQuestionActivity.this, "启动练习界面失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            // 根据待办标记显示铃铛红点
            if (redDotBell != null) {
                List<WrongQuestionRecord> lastWeekList = getLastWeekWrongList(wrongList);

                boolean pending = WrongPushStore.hasPending(this);
                String weekKey = WrongPushStore.currentWeekKey();
                boolean afterMon9 = WrongPushStore.isAfterThisMondayNine();
                
                // 检查用户特定的状态
                boolean userCleared = studentId != null && !studentId.isEmpty() 
                    ? WrongPushStore.isClearedForWeek(this, studentId, weekKey)
                    : false;

                // 任何一个为true都视为已清理
                boolean cleared = userCleared;

                
                // 显示红点条件：有pending 或者 (已过周一9点 且 本周未完成)
                boolean show = pending || (afterMon9 && !cleared);
                redDotBell.setVisibility(show ? View.VISIBLE : View.GONE);
                
                // 打印所有存储的值进行调试
                SharedPreferences sp = getSharedPreferences("wrong_push", MODE_PRIVATE);
                System.out.println("All stored values in onResume:");
                for (Map.Entry<String, ?> entry : sp.getAll().entrySet()) {
                    System.out.println(entry.getKey() + " : " + entry.getValue());
                }
            }
        } catch (Exception e) { 
            e.printStackTrace();
        }
    }

    //调用API获取错题
    private void loadWrongQuestions(String studentId) {
        new Thread(() -> {
            final ApiResponse<List<WrongQuestionRecord>> response = apiService.getWrongQuestionsByStudentId(studentId);
            runOnUiThread(() -> {
                if (response.getCode() == 200 && response.getData() != null) {
                    wrongList.clear();
                    wrongList.addAll(response.getData());
                    applyGroupingAndFilter();
                } else {
                    Toast.makeText(this, "获取错题集失败: " + response.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }).start();
    }


    //应用筛选的错题
    private void applyGroupingAndFilter() {
        List<WrongQuestionRecord> filtered = filterByTime(wrongList, currentFilter);
        List<Object> grouped = buildGroupedItems(filtered);
        adapter.updateData(grouped);
    }

    //时间筛选
    private List<WrongQuestionRecord> filterByTime(List<WrongQuestionRecord> list, TimeFilter filter) {
        if (filter == TimeFilter.ALL) return new ArrayList<>(list);
        LocalDate now = LocalDate.now();
        LocalDate weekStart = now.minusDays(now.getDayOfWeek().getValue() - 1); // 周一
        LocalDate monthStart = now.withDayOfMonth(1);
        List<WrongQuestionRecord> out = new ArrayList<>();
        for (WrongQuestionRecord r : list) {
            LocalDate d = parseToLocalDate(r.getDate());
            if (d == null) continue;
            if (filter == TimeFilter.WEEK) {
                if (!d.isBefore(weekStart)) out.add(r);
            } else if (filter == TimeFilter.MONTH) {
                if (!d.isBefore(monthStart)) out.add(r);
            }
        }
        return out;
    }


    //分组，相同日期放一组
    private List<Object> buildGroupedItems(List<WrongQuestionRecord> list) {
        Map<LocalDate, List<WrongQuestionRecord>> map = new HashMap<>();
        for (WrongQuestionRecord r : list) {
            LocalDate d = parseToLocalDate(r.getDate());
            if (d == null) continue;
            map.computeIfAbsent(d, k -> new ArrayList<>()).add(r);
        }
        List<LocalDate> dates = new ArrayList<>(map.keySet());
        // 按日期倒序
        Collections.sort(dates, Comparator.reverseOrder());

        List<Object> out = new ArrayList<>();
        for (LocalDate d : dates) {
            String header = d.getMonthValue() + "月" + d.getDayOfMonth() + "日";
            out.add(header);
            out.addAll(map.get(d));
        }
        return out;
    }

    //将String转为日期
    private LocalDate parseToLocalDate(String dateStr) {
        if (dateStr == null || dateStr.isEmpty()) return null;
        try {
            // 兼容 yyyy-MM-dd
            if (dateStr.length() >= 10) {
                String d = dateStr.substring(0, 10);
                return LocalDate.parse(d, DateTimeFormatter.ISO_LOCAL_DATE);
            }
            return LocalDate.parse(dateStr);
        } catch (Exception e) {
            try {
                // 尝试解析为日期时间
                LocalDateTime dt = LocalDateTime.parse(dateStr, DateTimeFormatter.ISO_DATE_TIME);
                return dt.toLocalDate();
            } catch (Exception ignored) { }
        }
        return null;
    }

    // 计算本周错题（周一开始）
    private List<WrongQuestionRecord> getThisWeekWrongList(List<WrongQuestionRecord> list) {
        LocalDate now = LocalDate.now();
        LocalDate weekStart = now.minusDays(now.getDayOfWeek().getValue() - 1);
        LocalDate weekEnd = weekStart.plusDays(6);
        List<WrongQuestionRecord> out = new ArrayList<>();
        for (WrongQuestionRecord r : list) {
            LocalDate d = parseToLocalDate(r.getDate());
            if (d == null) continue;
            if (!d.isBefore(weekStart) && !d.isAfter(weekEnd)) {
                out.add(r);
            }
        }
        return out;
    }

    // 计算上周错题（上周一到上周日）
    private List<WrongQuestionRecord> getLastWeekWrongList(List<WrongQuestionRecord> list) {
        LocalDate now = LocalDate.now();
        LocalDate thisWeekStart = now.minusDays(now.getDayOfWeek().getValue() - 1);
        LocalDate lastWeekStart = thisWeekStart.minusDays(7);
        LocalDate lastWeekEnd = thisWeekStart.minusDays(1);
        List<WrongQuestionRecord> out = new ArrayList<>();
        for (WrongQuestionRecord r : list) {
            LocalDate d = parseToLocalDate(r.getDate());
            if (d == null) continue;
            if (!d.isBefore(lastWeekStart) && !d.isAfter(lastWeekEnd)) {
                out.add(r);
            }
        }
        return out;
    }

    // 底部弹出选项：根据可用性显示“本周”与/或“上周”
    private void showPracticeOptions(List<WrongQuestionRecord> thisWeekList, List<WrongQuestionRecord> lastWeekList) {
        BottomSheetDialog dialog = new BottomSheetDialog(this);
        View content = getLayoutInflater().inflate(R.layout.bottom_sheet_wrong_practice_options, null);
        dialog.setContentView(content);

        View optThisWeek = content.findViewById(R.id.option_this_week);
        View optLastWeek = content.findViewById(R.id.option_last_week);
        TextView labelThisWeek = content.findViewById(R.id.label_this_week);
        TextView labelLastWeek = content.findViewById(R.id.label_last_week);
        TextView countThisWeek = content.findViewById(R.id.count_this_week);
        TextView countLastWeek = content.findViewById(R.id.count_last_week);
        Button btnConfirm = content.findViewById(R.id.btn_confirm);
        Button btnCancel = content.findViewById(R.id.btn_cancel);

        boolean hasThis = thisWeekList != null && !thisWeekList.isEmpty();
        boolean hasLast = lastWeekList != null && !lastWeekList.isEmpty();

        // 选项显示：不再隐藏无数据项，改为禁用并在右侧显示数量
        int cntThis = thisWeekList == null ? 0 : thisWeekList.size();
        int cntLast = lastWeekList == null ? 0 : lastWeekList.size();
        if (labelThisWeek != null) labelThisWeek.setText(getString(R.string.this_week));
        if (labelLastWeek != null) labelLastWeek.setText(getString(R.string.last_week));
        if (countThisWeek != null) countThisWeek.setText(getString(R.string.count_label, cntThis));
        if (countLastWeek != null) countLastWeek.setText(getString(R.string.count_label, cntLast));
        if (optThisWeek != null) { optThisWeek.setEnabled(hasThis); optThisWeek.setAlpha(hasThis ? 1f : 0.5f); }
        if (optLastWeek != null) { optLastWeek.setEnabled(hasLast); optLastWeek.setAlpha(hasLast ? 1f : 0.5f); }

        // -1 未选择；0 选择本周；1 选择上周
        final int[] selected = new int[]{-1};
        if (btnConfirm != null) {
            btnConfirm.setEnabled(false);
            btnConfirm.setAlpha(0.5f);
        }

        if (optThisWeek != null && hasThis) {
            optThisWeek.setOnClickListener(v -> {
                selected[0] = 0;
                applyOptionSelectedStyle(optThisWeek, true);
                if (optLastWeek != null) applyOptionSelectedStyle(optLastWeek, false);
                if (btnConfirm != null) { btnConfirm.setEnabled(true); btnConfirm.setAlpha(1f); }
            });
        }
        if (optLastWeek != null && hasLast) {
            optLastWeek.setOnClickListener(v -> {
                selected[0] = 1;
                applyOptionSelectedStyle(optLastWeek, true);
                if (optThisWeek != null) applyOptionSelectedStyle(optThisWeek, false);
                if (btnConfirm != null) { btnConfirm.setEnabled(true); btnConfirm.setAlpha(1f); }
            });
        }

        if (btnConfirm != null) {
            btnConfirm.setOnClickListener(v -> {
                if (selected[0] == -1) {
                    Toast.makeText(this, "请先选择时间范围", Toast.LENGTH_SHORT).show();
                    return;
                }
                List<WrongQuestionRecord> target = (selected[0] == 0) ? thisWeekList : lastWeekList;
                // 记住上次选择
                SharedPreferences sp = getSharedPreferences("wrong_practice", MODE_PRIVATE);
                sp.edit().putInt("last_range", selected[0]).apply();
                dialog.dismiss();
                startPracticeWith(target);
            });
        }

        if (btnCancel != null) {
            btnCancel.setOnClickListener(v -> dialog.dismiss());
        }

        // 初始：若仅一个可选项，则默认选中它；否则尝试读取上次选择并预选
        if (btnConfirm != null) { btnConfirm.setEnabled(false); btnConfirm.setAlpha(0.5f); }
        if (hasThis ^ hasLast) {
            if (hasThis && optThisWeek != null) {
                selected[0] = 0; applyOptionSelectedStyle(optThisWeek, true); if (btnConfirm != null) { btnConfirm.setEnabled(true); btnConfirm.setAlpha(1f);} }
            if (hasLast && optLastWeek != null) {
                selected[0] = 1; applyOptionSelectedStyle(optLastWeek, true); if (btnConfirm != null) { btnConfirm.setEnabled(true); btnConfirm.setAlpha(1f);} }
        } else {
            if (optThisWeek != null) applyOptionSelectedStyle(optThisWeek, false);
            if (optLastWeek != null) applyOptionSelectedStyle(optLastWeek, false);
            // 读取上次选择
            SharedPreferences sp = getSharedPreferences("wrong_practice", MODE_PRIVATE);
            int last = sp.getInt("last_range", -1);
            if (last == 0 && hasThis && optThisWeek != null) { selected[0] = 0; applyOptionSelectedStyle(optThisWeek, true); if (btnConfirm != null) { btnConfirm.setEnabled(true); btnConfirm.setAlpha(1f);} }
            if (last == 1 && hasLast && optLastWeek != null) { selected[0] = 1; applyOptionSelectedStyle(optLastWeek, true); if (btnConfirm != null) { btnConfirm.setEnabled(true); btnConfirm.setAlpha(1f);} }
        }

        dialog.show();
    }

    // 为选项应用选中与未选中样式
    private void applyOptionSelectedStyle(View v, boolean selected) {
        if (v == null) return;
        v.setBackgroundResource(selected ? R.drawable.bg_option_selected : R.drawable.bg_option_unselected);
    }

    // 启动练习页，传入选中的错题集合
    private void startPracticeWith(List<WrongQuestionRecord> list) {
        if (list == null || list.isEmpty()) {
            Toast.makeText(this, "所选时间范围暂无错题", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(WrongQuestionActivity.this, WrongQuestionPracticeActivity.class);

        ArrayList<String> questions = new ArrayList<>();
        ArrayList<String> answers = new ArrayList<>();
        ArrayList<Integer> wrongIds = new ArrayList<>();
        for (WrongQuestionRecord record : list) {
            String q = record.getQuestion();
            String a = record.getAnswer();
            if (q != null && !q.isEmpty() && a != null && !a.isEmpty()) {
                questions.add(q);
                answers.add(a);
            }
            if (record.getWrongId() != null) wrongIds.add(record.getWrongId());
        }
        if (!questions.isEmpty() && questions.size() == answers.size()) {
            intent.putStringArrayListExtra("questions", questions);
            intent.putStringArrayListExtra("answers", answers);
        }
        intent.putExtra("wrong_questions_count", list.size());
        intent.putIntegerArrayListExtra("wrong_question_ids", wrongIds);
        startActivity(intent);
    }

    // 从推送入口进入：附带 from_push 标识，便于结果页完成后做清理
    private void startPracticeFromPush(List<WrongQuestionRecord> list) {
        if (list == null || list.isEmpty()) {
            Toast.makeText(this, "上周暂无错题", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(WrongQuestionActivity.this, WrongQuestionPracticeActivity.class);

        ArrayList<String> questions = new ArrayList<>();
        ArrayList<String> answers = new ArrayList<>();
        ArrayList<Integer> wrongIds = new ArrayList<>();
        for (WrongQuestionRecord record : list) {
            String q = record.getQuestion();
            String a = record.getAnswer();
            if (q != null && !q.isEmpty() && a != null && !a.isEmpty()) {
                questions.add(q);
                answers.add(a);
            }
            if (record.getWrongId() != null) wrongIds.add(record.getWrongId());
        }
        if (!questions.isEmpty() && questions.size() == answers.size()) {
            intent.putStringArrayListExtra("questions", questions);
            intent.putStringArrayListExtra("answers", answers);
        }
        intent.putExtra("from_push", true);
        intent.putIntegerArrayListExtra("wrong_question_ids", wrongIds);
        startActivity(intent);
    }
}